package com.yjf.ljr.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.yjf.ljr.R;

/**
 * 应用升级模块
 */
public class UpdateSoftActivity extends IjActivity implements OnClickListener{

	private static final int REFRESH_PROGRESS = 0x0000;
	private static final int ERROR = 0x0001;

	@ID("tvNotiUpdate")
	private TextView mTvNoti;
	@ID("btnLeftUpdateactivity")
	private ImageButton mBtnBack;
	@ID("btnReDownLoad")
	private Button mBtnReDownLoad;
	@ID("pbUpdate")
	private ProgressBar mPb;

	private String mUpdateURL;
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case REFRESH_PROGRESS:
				mTvNoti.setText("正在下载文件,请稍候...");
				mBtnBack.setVisibility(View.GONE);
				mBtnReDownLoad.setVisibility(View.GONE);
				mPb.setProgress((Integer)msg.obj);
				break;
			case ERROR:
				mBtnBack.setVisibility(View.VISIBLE);
				mBtnReDownLoad.setVisibility(View.VISIBLE);
				mTvNoti.setText("下载失败,请重试");
				break;
			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_update);

		mUpdateURL = getIntent().getStringExtra("updateUrl");
		mBtnReDownLoad.setOnClickListener(this);
		mBtnBack.setOnClickListener(this);
		updateOnThread(mUpdateURL);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnReDownLoad:
			updateOnThread(mUpdateURL);
			break;
		case R.id.btnLeftUpdateactivity:
			finish();
			break;
		}
	}
	
	private void updateOnThread(final String updateUrl){
		new Thread() {
			@Override
			public void run() {
				doUpdate(updateUrl);
			}
		}.start();
	}
	
	public void doUpdate(String updateUrl) {
		File apkFile = null;
		File updateDir = null;
		try {
			URL url = new URL(updateUrl);
			HttpURLConnection hc = (HttpURLConnection) url.openConnection();
			InputStream in = hc.getInputStream();
			hc.setConnectTimeout(15000);
			int totalSize = hc.getContentLength();
			int curSize = 0;
			int progress = 0;

			if (android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment.getExternalStorageState())) {
				updateDir = new File(Environment.getExternalStorageDirectory().getPath() + "/invest/apk/");
			} else { 
				String dataPath = getFilesDir().getPath(); /** /data/data/com.yjf.yfjr/files **/
				updateDir = new File(dataPath + "/apk");
			}

			if (!updateDir.exists()) {
				updateDir.mkdirs();
			}
			apkFile = new File(updateDir.getPath(), "invest.apk");
			if (apkFile.exists()) {
				apkFile.delete();
			}
			apkFile.createNewFile();

			// 修改文件夹及安装包的权限,供第三方应用访问
			try {
				Runtime.getRuntime().exec("chmod 705 " + updateDir.getPath());
				Runtime.getRuntime().exec("chmod 604 " + apkFile.getPath());
			} catch (Exception e) {
				e.printStackTrace();
			}

			FileOutputStream out = new FileOutputStream(apkFile);
			byte[] bytes = new byte[1024];
			int c;
			while ((c = in.read(bytes)) != -1) {
				out.write(bytes, 0, c);
				curSize += c;
				progress = curSize * 100 / totalSize;
				Message msg = Message.obtain(mHandler, REFRESH_PROGRESS, progress);
				mHandler.sendMessage(msg);
			}
			in.close();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			UpdateSoftActivity.this.mHandler.sendEmptyMessage(ERROR);
			return;
		}

		/*
		 * final String sdcardpath =
		 * Environment.getExternalStorageDirectory().getPath(); final String
		 * oldapk_filepath = sdcardpath + File.separator + "old.apk"; final
		 * String newapk_savepath = sdcardpath + File.separator + "new.apk";
		 * final String patchpath = sdcardpath + File.separator + "u.apk";
		 * 
		 * DiffPatch diffPatch = new DiffPatch();
		 * diffPatch.applyPatch(oldapk_filepath, newapk_savepath, patchpath);
		 */

		String apkUpdatePath = apkFile.getPath();
		if (apkFile != null) {
			// 增量升级
/*			mChannel = AppUtil.getChanel(this);
			if ("20".equals(mChannel) && !mIsFullUpdate) {
				String appDataPath = AppUtil.getSourceDir(this); // path:/data/app/com.feinno.innervation-1.apk
				try {
					Runtime.getRuntime().exec("chmod 604 " + appDataPath);
				} catch (Exception e) {
					e.printStackTrace();
				}
				if (updateDir.getPath().endsWith(File.separator)) {
					apkUpdatePath = updateDir.getPath() + "job_merge.apk";
				} else {
					apkUpdatePath = updateDir.getPath() + File.separator + "job_merge.apk";
				}
				DiffPatch diffPatch = new DiffPatch();
				diffPatch.applyPatch(appDataPath, apkUpdatePath, apkFile.getPath());
			}*/

			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.setDataAndType(Uri.parse("file://" + apkUpdatePath), "application/vnd.android.package-archive");
			startActivity(intent);
			UpdateSoftActivity.this.finish();
		}
	}
}